import React, {useState, useCallback} from 'react'
import useDynamicCache from '@/store/modules/dynamicCache'
import useCurrentPage from '@/store/modules/currentPage'

function useCacheAlive<T>(initialValue: T, keyReal: string = '', ): [T | undefined, (value: T) => void] {
  const currentPage = useCurrentPage();
  const key = `${currentPage.currentName}$-$${keyReal}`
  const baseUseDynamicStore = useDynamicCache()
  const storage = baseUseDynamicStore.storage as Record<string, T>;
  const setStorage = baseUseDynamicStore.set;

  const [value, setValue] = useState<T | undefined>(() => storage[key] || initialValue);

  const setValueFromStore = useCallback((newValue: T) => {
    setStorage(key, newValue);
    setValue(newValue);
  }, [key, setStorage]);

  return [value, setValueFromStore];
}

export default useCacheAlive